#include <QCoreApplication>
#include <QProcess>
#include <QDir>
#include <QDebug>
#include <csignal>

// 全局变量用于信号处理
QProcess* g_process = nullptr;

// 信号处理函数
void signalHandler(int signal)
{
    qDebug() << "Received signal:" << signal;
    if (g_process && g_process->state() == QProcess::Running) {
        qDebug() << "Terminating qmlscene process...";
        g_process->terminate(); // 先尝试正常终止
        if (!g_process->waitForFinished(3000)) { // 等待3秒
            qDebug() << "Force killing qmlscene process...";
            g_process->kill(); // 强制杀死
        }
    }
    QCoreApplication::quit();
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QProcess process;
    g_process = &process; // 设置全局指针

    // 注册信号处理函数
    std::signal(SIGINT, signalHandler);  // Ctrl+C
    std::signal(SIGTERM, signalHandler); // 终止信号
#ifdef Q_OS_UNIX
    std::signal(SIGHUP, signalHandler);  // 终端关闭
#endif

    // 使用 CMake 传递的目录
    QDir workingDir(STARTUP_WORKDIR);

    if (!workingDir.exists()) {
        qCritical() << "Working directory not found:" << workingDir;
        return 1;
    }

    QString qmlFile = STARTUP_QMLFILE;

    if (!QFile::exists(qmlFile)) {
        qCritical() << "QML file not found:" << qmlFile;
        return 1;
    }

    process.setWorkingDirectory(workingDir.absolutePath());

    // 设置环境变量（根据你的需求）
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("QML2_IMPORT_PATH", workingDir.absolutePath());
    process.setProcessEnvironment(env);

    process.setProgram("qmlscene");
    process.setArguments({qmlFile});

    // 连接输出信号
    QObject::connect(&process, &QProcess::readyReadStandardOutput, [&process]() {
        QByteArray output = process.readAllStandardOutput();
        qDebug().noquote() << output.trimmed();
    });

    QObject::connect(&process, &QProcess::readyReadStandardError, [&process]() {
        QByteArray error = process.readAllStandardError();
        qCritical().noquote() << error.trimmed();
    });

    qDebug() << "Working directory:" << workingDir.absolutePath();
    qDebug() << "QML file:" << qmlFile;

#ifdef STARTUP_ATTACH
    // 同步启动并等待结束
    process.start();

    if (!process.waitForStarted()) {
        qCritical() << "Failed to start qmlscene";
        return 1;
    }

    qDebug() << "qmlscene started successfully, PID:" << process.processId();

    // 等待进程结束
    process.waitForFinished(-1); // -1 表示无限等待

    qDebug() << "qmlscene exited with code:" << process.exitCode();

    return process.exitCode();
#else
    bool started = process.startDetached();

    if (!started) {
        qCritical() << "Failed to start qmlscene";
        return 1;
    }

    qDebug() << "qmlscene started successfully";

    return 0;
#endif
}
